package controller

import (
	"strconv"

	"gostore/dao"
	"gostore/router"

	com "gostore/common"

	"github.com/gin-gonic/gin"
)

type UserControllerT struct {
	BaseControllerT
}

var UserController = UserControllerT{}

func (o UserControllerT) List(c *gin.Context) {
	req := new(dao.ReqUserQuery)

	err := c.ShouldBindQuery(req)
	if err != nil {
		com.Err(c, 503, "错误的参数")
		return
	}

	userList, count, err := dao.UserDao.UserList(req)
	if err != nil {
		com.Err(c, 503, "查询失败")
		return
	}

	mdata := make(map[string]interface{}, 0)
	mdata["list"] = userList
	mdata["count"] = count
	com.Ok(c, mdata)
}

func (o UserControllerT) StoreOrderList(c *gin.Context) {
	req := new(dao.Query)

	err := c.ShouldBindQuery(req)
	if err != nil {
		com.Err(c, 503, "错误的参数")
		return
	}

	uidStr := c.Param("uid")

	uid, err := strconv.Atoi(uidStr)

	if err != nil {
		com.Err(c, 503, "无效的id")
		return
	}

	list, count, err := dao.GetUserStoreOrderList(uid, req)
	if err != nil {
		com.Err(c, 503, "查询失败")
		return
	}

	mdata := make(map[string]interface{}, 0)
	mdata["list"] = list
	mdata["count"] = count
	com.Ok(c, mdata)
}

func (o UserControllerT) AddNewRoutes() {
	router.AddRouteGroup("api/users", []router.Route{
		router.Route{
			Method:  router.MGet,
			Path:    "",
			Handler: o.List,
		},
	})

	router.AddRouteGroup("api/users", []router.Route{
		router.Route{
			Method:  router.MGet,
			Path:    "/:uid/storeOrder",
			Handler: o.StoreOrderList,
		},
	})
}
